package com.device.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * @author chengyadong
 * @date 2023/12/8 15:34
 * @description 数据源配置
 */
@Configuration
public class JdbcTemplateConfig {
	@Value("${spring.datasource.driver-class-name}")
	private String driveClassName;

	@Value("${spring.datasource.username}")
	private String userName;

	@Value("${spring.datasource.password}")
	private String passWord;

	@Value("${spring.datasource.url}")
	private String url;

	@Bean
	public JdbcTemplate jdbcTemplate() throws PropertyVetoException {
		return new JdbcTemplate(dataSource());
	}

	/*初始化数据源*/
	@Bean(name = "dataSource")
	public DataSource dataSource() throws PropertyVetoException {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setDriverClassName(driveClassName);
		dataSource.setUrl(url);
		dataSource.setUsername(userName);
		dataSource.setPassword(passWord);
		dataSource.setInitialSize(1);
		return dataSource;
	}

	//DataSource配置：载入-------->事务管理配置
	@Bean
	public DataSourceTransactionManager txManager() throws PropertyVetoException {
		return new DataSourceTransactionManager(dataSource());
	}
}
